class ApiCache {
    static instance;
    maxSize = 5;
    cache = new Map();
    pendingRequests = new Map();

    static getInstance() {
        if (!ApiCache.instance) {
            ApiCache.instance = new ApiCache();
        }
        return ApiCache.instance;
    }

    generateKey(params) {
        return JSON.stringify(params);
    }

    async getData(params) {
        const key = this.generateKey(params);

        // 命中缓存
        if (this.cache.has(key)) return this.cache.get(key);

        // 处理并发
        if (this.pendingRequests.has(key)) {
            return this.pendingRequests.get(key);
        }

        // 发起新请求
        const request = this.fetchRemoteData(params)
            .then((data) => {
                this.cache.set(key, data);
                this.pendingRequests.delete(key);
                this.cleanCache();
                return data;
            })
            .catch((err) => {
                this.pendingRequests.delete(key);
                throw err;
            });

        this.pendingRequests.set(key, request);
        return request;
    }

    cleanCache() {
        if (this.cache.size > this.maxSize) {
            // 删除最旧的缓存
            const oldestKey = this.cache.keys().next().value;
            this.cache.delete(oldestKey);
        }
    }

    async fetchRemoteData(params) {
        // 实际网络请求逻辑
        return await api.get('/data', { params });
    }
}
